use(["public/javascripts/service/addressService.js",
    "public/javascripts/widget/slider/slider.js",
    "public/javascripts/widget/mtable/mtable.js",
    "public/javascripts/address/addressView.js",
    "public/javascripts/widget/dialog/dialog.js",
    "public/javascripts/widget/prompt/prompt.js",
    "public/common/classNames.js",
    "public/javascripts/widget/select/select.js",
    "public/javascripts/widget/myInput/myInput.js"
    ],  function(addressService, SliderComponent, mtableModule, addressView, DialogComponent, PromptComponent, classNames, selectFactory, MyInputComponent) {
    var cn = classNames;
    var homeCountry = "中国";
    var PageComponent = React.createClass({
        update: function() {
            this.setState();
        },
        mtable: null,
        clearAddressSelect: function() {
            this.state.data["province"] = "";
            this.state.data["provinceId"] = "";
            this.state.data["city"] = "";
            this.state.data["cityId"] = "";
            this.state.data["area"] = "";
            this.state.data["districtId"] = "";
            this.state.data["street"] = "";
            this.state.data["streetId"] = "";
            this.state.data["division"] = "";
            this.state.data["airSea"] = "";
            this.state.data["airSeaId"] = "";
        },
        clearAddressData: function() {
            this.state.data["id"] = "";
            this.state.data["name"] = "";
            this.state.data["email"] = "";
            this.state.data["country"] = "";
            this.state.data["countryCode"] = "";
            this.state.data["province"] = "";
            this.state.data["provinceId"] = "";
            this.state.data["city"] = "";
            this.state.data["cityId"] = "";
            this.state.data["area"] = "";
            this.state.data["districtId"] = "";
            this.state.data["street"] = "";
            this.state.data["streetId"] = "";
            this.state.data["division"] = "";
            this.state.data["airSea"] = "";
            this.state.data["airSeaId"] = "";
            this.state.data["postcode"] = "";
            this.state.data["email"] = "";
            this.state.data["mobilephone"] = "";
            this.state.data["telephone"] = "";
            this.state.data["addressDetail"] = "";
            this.state.data["isDefault"] = false;
            this.state.data["isHideAdressBox"] = true;
            this.state.data["isHideDivisionBox"] = true;
            this.state.data["isShowPort"] = false;

            this.state.data["transportTypeName"] = "全球速递";
            this.state.data["transportType"] = 11;
            this.state.data["isOrdinary"] = true;
        },
        setAddressData: function(editData) {
            this.state.data["id"] = editData.id;
            this.state.data["name"] = editData.name;
            this.state.data["email"] = editData.email;
            this.state.data["country"] = editData.countryCode ? (editData.countryName + '(' + editData.countryCode + ')') : editData.countryName;
            this.state.data["countryCode"] = editData.countryCode;
            this.state.data["province"] = editData.provinceName;
            this.state.data["provinceId"] = editData.provinceId;
            this.state.data["city"] = editData.cityName;
            this.state.data["cityId"] = editData.cityId;
            this.state.data["area"] = editData.districtName;
            this.state.data["districtId"] = editData.districtId;
            this.state.data["street"] = editData.streetName;
            this.state.data["streetId"] = editData.streetId;
            this.state.data["division"] = editData.cityName;
            this.state.data["postcode"] = editData.postcode;
            this.state.data["mobilephone"] = editData.phone;
            this.state.data["telephone"] = editData.telPhone;
            this.state.data["isDefault"] = editData.isDefault;
            this.state.data["addressDetail"] = this.state.data["addDetails"] = editData.address;
            this.state.data["transportType"] = editData.transportType;
            this.state.data["transportTypeName"] = editData.transportTypeName;
            if(this.state.active === 2){
                this.state.data["airSea"] = editData.transportEnglishName ? (editData.transportName+'('+editData.transportEnglishName+')') : editData.transportEnglishName;
            }else if(this.state.active === 3){
                this.state.data["airSea"] = editData.transportCode ? (editData.transportName+'('+editData.transportCode+')') : editData.transportEnglishName;
            }else {
                this.state.data["airSea"] = editData.transportName;
            }
            this.state.data["airSeaId"] = editData.transportId;

            if(editData.transportType == this.state.data['seaId'] || editData.transportType == this.state.data['airId']){
                this.state.data['isHideAdressBox'] = false;
                this.state.data['isHideDivisionBox'] = false;
            }else{
                this.state.data['isHideAdressBox'] = true;
                this.state.data['isHideDivisionBox'] = true;
            }
        },
        clearHomeCountrySelect: function() {
            addressView.clearAllHomeCountrySelect();
        },
        componentDidMount: function() {
            var self = this;
            this.mtable = mtableModule.init('#mtable');
            //海运、空运地址类型Id
            this.state.data['seaId'] = 1, this.state.data['airId'] = 6;
            this.state.data['isOrdinary'] = true;   //初始化
            //地址类型下拉框
            addressView.initAddressTypeSelect(selectFactory, addressService, function(item){
                if(item.id == self.state.data['seaId'] || item.id == self.state.data['airId']){
                    self.state.data['isOrdinary'] = false;
                }else{
                    self.state.data['isOrdinary'] = true;
                }

                self.state.data["transportTypeName"] = item.name;
                self.state.data["transportType"] = item.id;

                //清空海运、航运数据
                self.state.data["airSea"] = '';
                self.state.data["airSeaId"] = '';
                self.state.data["addDetails"] = '';
                
                self.state.data["country"] = "";
                self.state.data["countryCode"] = "";
                self.state.data["province"] = "";
                self.state.data["provinceId"] = "";
                self.state.data["city"] = "";
                self.state.data["cityId"] = "";
                self.state.data["area"] = "";
                self.state.data["districtId"] = "";
                self.state.data["street"] = "";
                self.state.data["streetId"] = "";
                self.state.data["division"] = "";
                self.state.data["addressDetail"] = "";

                self.apply();
            });

            //初始化国家下拉框
            addressView.initCountrySelect(selectFactory, addressService, '', function(name, countryCode) {
                self.state.data["country"] = countryCode ? (name + '('+ countryCode +')') : name;
                self.state.data["countryCode"] = countryCode;
                self.clearAddressSelect();
                if(self.state.active !== 1){
                    self.state.data["addressDetail"] = "";
                    if(countryCode !== undefined){
                        self.state.data["isShowPort"] = true;
                    }else{
                        self.state.data["isShowPort"] = false;
                    }
                }
                if(name == homeCountry) {
                    self.state.data["isHideAdressBox"] = false;
                    self.state.data["isHideDivisionBox"] = true;
                    self.clearHomeCountrySelect();
                    self.apply();
                } else if(!$.trim(name)) {
                    self.state.data["isHideAdressBox"] = true;
                    self.state.data["isHideDivisionBox"] = true;
                    self.apply();
                } else {
                    self.state.data["isHideDivisionBox"] = false;
                    addressView.setDivisionList(addressService, '');
                    self.state.data["isHideAdressBox"] = true;
                    self.apply();
                }
            });
            addressView.initProvinceSelect(selectFactory, addressService, function(name, provinceId) {
                self.state.data["province"] = name;
                self.state.data["provinceId"] = provinceId;
                self.state.data["city"] = "";
                self.state.data["cityId"] = "";
                self.state.data["area"] = "";
                self.state.data["districtId"] = "";
                self.state.data["street"] = "";
                self.state.data["streetId"] = "";
                self.state.data["division"] = "";
                self.apply();
            });
            addressView.initCitySelect(selectFactory, addressService, function(name, cityId) {
                self.state.data["city"] = name;
                self.state.data["cityId"] = cityId;
                self.state.data["area"] = "";
                self.state.data["districtId"] = "";
                self.state.data["street"] = "";
                self.state.data["streetId"] = "";
                self.state.data["division"] = "";
                self.apply();
            });
            addressView.initAreaSelect(selectFactory, addressService, function(name, districtId) {
                self.state.data["area"] = name;
                self.state.data["districtId"] = districtId;
                self.state.data["street"] = "";
                self.state.data["streetId"] = "";
                self.state.data["division"] = "";
                self.apply();
            });
            addressView.initStreetSelect(selectFactory, addressService, function(name, streetId) {
                self.state.data["street"] = name;
                self.state.data["streetId"] = streetId;
                self.state.data["division"] = "";
                self.apply();
            });
            addressView.initDivisionSelect(selectFactory, addressService, function(name, cityId) {
                self.state.data["division"] = name;
                self.state.data["cityId"] = cityId;
                self.apply();
            });
            //海运、航运数据下拉
            addressView.initSeaAirSelect({
                'countryCode': '',
                'airSeaType': self.state.active === 2 ? 1 : 6
            }, selectFactory, addressService, '', function(item){
                self.state.data["airSea"] = item.nameCode;
                self.state.data["airSeaId"] = item.id;
                self.state.data["addDetails"] = item.address ? item.address : '';
                self.state.data["addressDetail"] = item.address ? item.address : '';
                self.apply();
            });
            addressView.closeInputAutoComplete();
        },
        receiveMsg: function(data) {

        },
        cancel: function() {
            this.refs["email"].hideErrorMsg();
            addressView.hideMiddel();
        },
        edit: function(editData, event) {
            if(this.state.active === 1){
                $("#addressDetail").removeAttr("readonly");
            }else{
                $("#addressDetail").attr("readonly","readonly");
            }
            addressView.setAutoCompleteOff();
            addressView.setAddressId(editData);

            this.state.data.promptTile = "编辑地址";
            this.setAddressData(editData);
            var placeHolder = this.state.active === 2 ? "请输入名称" : "请输入名称或三字码";
            addressView.setPlaceHolder(placeHolder);
            if(editData.countryName == homeCountry) {
                this.state.data["isHideDivisionBox"] = true;
                this.state.data["isHideAdressBox"] = false;
            } else {
                this.state.data["isHideAdressBox"] = true;
                this.state.data["isHideDivisionBox"] = false;
            }
            if(this.state.active !== 1){
                this.state.data.isShowPort = true;
            }
            this.apply();
            var self = this;
            addressView.showMiddle();
            //海运、航运数据下拉
            addressView.initSeaAirSelect({
                'countryCode': editData.countryCode,
                'airSeaType': self.state.active === 2 ? 1 : 6
            }, selectFactory, addressService, '', function(item){
                self.state.data["airSea"] = item.nameCode;
                self.state.data["airSeaId"] = item.id;
                self.state.data["addDetails"] = item.address ? item.address : '';
                self.state.data["addressDetail"] = item.address ? item.address : '';
                self.apply();
            });
        },
        showCountryList: function() {
            addressView.setCountryList(addressService);//初始化国家下来框
        },
        initAirSeaPort: function(){
            addressView.setSeaAirList({
                'countryCode': this.state.data['countryCode'],
                'airSeaType': this.state.active === 2 ? 1 : 6
            }, addressService);
            // //海运、航运数据下拉
            // addressView.initSeaAirSelect({
            //     'countryCode': self.state.data['countryCode'],
            //     'airSeaType': self.state.active === 2 ? 1 : 6
            // }, selectFactory, addressService, '', function(item){
            //     self.state.data["airSea"] = item.nameCode;
            //     self.state.data["airSeaId"] = item.id;
            //     self.state.data["addDetails"] = item.address ? item.address : '';
            //     self.state.data["addressDetail"] = item.address ? item.address : '';
            //     self.apply();
            // });
        },
        add: function() {
            var _this = this;
            if(this.state.data.address.length < 10){
                this.state.data.promptTile = "添加地址";
                addressView.showMiddle();
                this.clearAddressData();
                this.apply();
                if(this.state.active === 1){
                    $("#addressDetail").removeAttr("readonly");
                }else{
                    $("#addressDetail").attr("readonly","readonly");
                    var placeHolder = this.state.active === 2 ? "请输入名称" : "请输入名称或三字码";
                    addressView.setPlaceHolder(placeHolder);
                    var _this = this;
                    //海运、航运数据下拉
                    addressView.initSeaAirSelect({
                        'countryCode': '',
                        'airSeaType': _this.state.active === 2 ? 1 : 6
                    }, selectFactory, addressService, '', function(item){
                        _this.state.data["airSea"] = item.nameCode;
                        _this.state.data["airSeaId"] = item.id;
                        _this.state.data["addDetails"] = item.address ? item.address : '';
                        _this.state.data["addressDetail"] = item.address ? item.address : '';
                        _this.apply();
                    });
                }
            }else{
                var alertMsg = "";
                var type = easyMe.getQueryString('type');
                if(type === "send"){
                    if(this.state.active === 1){
                        alertMsg = "该客户发货人速递地址个数已达上限!";
                    }else if(this.state.active === 2){
                        alertMsg = "该客户发货人海运地址个数已达上限!";
                    }else{
                        alertMsg = "该客户发货人空运地址个数已达上限!";
                    }
                }else if(type === "receive"){
                    if(this.state.active === 1){
                        alertMsg = "该客户收货人速递地址个数已达上限!";
                    }else if(this.state.active === 2){
                        alertMsg = "该客户收货人海运地址个数已达上限!";
                    }else{
                        alertMsg = "该客户收货人空运地址个数已达上限!";
                    }
                }else if(type === "pick"){
                    alertMsg = "该客户提货地址个数已达上限!";
                }else {
                    alertMsg = "该客户地址个数已达上限!";
                }
                PromptComponent.init({'type': 'warning', "msg": alertMsg}).show();
            }
        },
        checkForm: function() {
            var isOk = true;
            var keys = ["name", "address", "province", "city", "area", "street", "division", "addressDetail","airSea", "postcode"];
            if(this.state.active === 1){
                if(this.state.data["country"] == '中国(CN)') {//中国
                    for(var index = 0; index < keys.length; index++) {
                        if(keys[index] != "division" && keys[index] != "airSea" && keys[index] != "area" && keys[index] != "street") {
                            if(!this.refs[keys[index]].isOk()) {
                                isOk = false;
                            }
                        }
                    }
                } else {
                    for(var index = 0; index < keys.length; index++) {
                        if(keys[index] != "province" && keys[index] != "city" && keys[index] != "area" && keys[index] != "street" && keys[index] != "airSea") {
                            if(!this.refs[keys[index]].isOk()) {
                                isOk = false;
                            }
                        }
                    }
                }
            }else{
                 for(var index = 0; index < keys.length; index++) {
                     if(
                         keys[index] != "province" &&
                         keys[index] != "city" &&
                         keys[index] != "area" &&
                         keys[index] != "street" &&
                         keys[index] != "addressDetail" &&
                         keys[index] != "division"
                     ){
                         if(!this.refs[keys[index]].isOk()){
                             isOk = false;
                         }
                     }
                 }
            }
            if($("#email").next("span").hasClass("error-msg")){
                isOk = false;
            }
            if($.trim($("#mobilephone").val()) === "" && $.trim($("#telephone").val()) === ""){
                $("#mobilephone").addClass("required");
                isOk = false;
                return isOk;
            }else{
                if((this.refs["telephone"].isOk() && $.trim($("#telephone").val()) !== "") || (this.refs["mobilephone"].isOk() && $.trim($("#mobilephone").val()) !== "")){
                    if(!$("#mobilephone").hasClass("required") && !$("#telephone").hasClass("required") && !$("#telephone").next("span").hasClass("error-msg")){
                        $("#mobilephone, #telephone").removeClass("required");
                        return isOk;
                    }else {
                        isOk = false;
                        return isOk;
                    }
                }else {
                    isOk = false;
                    return isOk;
                }
            }

        },
        save: function() {
            addressView.setAutoCompleteOff();
            if(!this.checkForm()) {
                return;
            }
            if(this.state.active === 1){
                this.state.data.transportType = 11;
            }else if(this.state.active == 2){
                this.state.data.transportType = 1;
            }else{
                this.state.data.transportType = 6;
            }
            var _this = this,
                _type = 1;
            if(easyMe.getQueryString('type') === 'send'){
                _type = 1;
            }else if(easyMe.getQueryString('type') === 'receive'){
                _type = 2;
            }else if(easyMe.getQueryString('type') === 'pick'){
                _type = 3;
                this.state.data.transportType = "";
            }else{
                _type = 1;
            }
            var _transportType = this.state.data.transportType;
            if(this.state.active !== 1){
                this.state.data["province"] = "";
                this.state.data["city"] = "";
                this.state.data["area"] = "";
                this.state.data["street"] = "";
                this.state.data["division"] = "";
                this.state.data["addressDetail"] = "";
                this.state.data["addDetails"] = "";
            }
            addressView.save(this.state.data, addressService, function(result) {
                if(result.errorCode == 0) {
                    //location.reload();
                    var config = {
                        'urlParams': {
                            'type': _type,
                            'transportType': _transportType
                        }
                    };
                    addressService.searchReceiveAddress(config, function(res){
                        if(res.errorCode === 0){
                            _this.state.data.address =  res.data;
                            _this.setState();
                            PromptComponent.init({'type': 'success', "msg": result.msg}).show();
                            addressView.hideMiddel();
                            _this.mtable.cancelSelect();
                        }
                    });
                } else {
                    PromptComponent.init({'type': 'warning', "msg": result.msg}).show();
                }
            });
        },
        validateMob: function(){
            if(this.refs["mobilephone"].isOk() && $.trim($("#mobilephone").val()) !== ""){
                $("#mobilephone").removeClass("required");
            }
        },
        validateTel: function(){
            if(this.refs["telephone"].isOk() && $.trim($("#telephone").val()) !== ""){
                if($.trim($("#mobilephone").val()) === ""){
                    $("#mobilephone").removeClass("required");
                }
            }else if($.trim($("#telephone").val()) === ""){
                $("#telephone").next("span").html("").removeClass("error-msg");
            }
        },
        deleteData: function() {
            var selectData = this.mtable.getSelectData();
            var ids = [];
            for(var index = 0; index < selectData.length; index++) {
                ids.push(selectData[index].id);
            }
            if(selectData.length == 0) {
                PromptComponent.init({'type': 'warning', "msg":"请先选择数据！"}).show();
                return;
            }
            if(this.state.active === 1){
                this.state.data.transportType = 11;
            }else if(this.state.active == 2){
                this.state.data.transportType = 1;
            }else{
                this.state.data.transportType = 6;
            }
            var _this = this,
                _type = 1;
            if(easyMe.getQueryString('type') === 'send'){
                _type = 1;
            }else if(easyMe.getQueryString('type') === 'receive'){
                _type = 2;
            }else if(easyMe.getQueryString('type') === 'pick'){
                _type = 3;
                this.state.data.transportType = "";
            }else{
                _type = 1;
            }
            var _transportType = this.state.data.transportType;
            DialogComponent.init({'type':'confirm','msg':'确定删除已选地址？', "success": function() {
                addressService.deleteAddress(ids, function(result) {
                    PromptComponent.init({'type': 'success', "msg": result.msg}).show();
                    var config = {
                        'urlParams': {
                            'type': _type,
                            'transportType': _transportType
                        }
                    };
                    addressService.searchReceiveAddress(config, function(res){
                        if(res.errorCode === 0){
                            _this.state.data.address =  res.data;
                            _this.setState();
                            PromptComponent.init({'type': 'success', "msg": result.msg}).show();
                            addressView.hideMiddel();
                            _this.mtable.cancelSelect();
                        }
                    });
                });
            }}).show();
        },
        setAddress: function(editData, event) {
            var _this = this;
            var type = editData.type;
            var id = editData.id;
            var transportType = editData.transportType;
            addressView.setDefaultAddress(type, id, transportType, addressService, function(result) {
                if(result.errorCode == 0) {
                    PromptComponent.init({'type': 'success', "msg": result.msg}).show();
                    var config = {
                        'urlParams': {
                            'type': type,
                            'transportType': transportType
                        }
                    };
                    addressService.searchReceiveAddress(config, function(res){
                        if(res.errorCode === 0){
                            _this.state.data.address =  res.data;
                            _this.setState();
                        }
                    });
                } else {
                    PromptComponent.init({'type': 'warning', "msg": result.msg}).show();
                }
            });
        },
        toggleTab: function (index) {
            $("#prompt").remove();
            var _this = this;
            if (this.state.active === index) return;
            //this.setState({ active: index });
            this.mtable.cancelSelect();
            var transportType = 11, type = 1;
            if(index === 1){
                transportType = 11;
            }else if(index === 2){
                transportType = 1;
            }else{
                transportType = 6;
            }
            if(easyMe.getQueryString('type') === 'send'){
                type = 1;
            }else if(easyMe.getQueryString('type') === 'receive'){
                type = 2;
            }else{
                type = 3;
                transportType = "";
            }
            var params = {
                "urlParams": {
                    "type": type,
                    "transportType": transportType
                }
            }
            addressService.searchReceiveAddress(params, function(res){
                if(res.errorCode === 0){
                    _this.state.data.address = res.data;
                    _this.state.active = index;
                    _this.apply();
                }
            });
        },
        getInitialState: function () {
            this.props.data.isHideAdressBox = true;
            this.props.data.isHideDivisionBox = true;
            this.props.data.isHideAdressDetailBox = false;
            this.props.data.isShowPort = false;
            this.props.data.mobilephone = "";
            this.props.data.telephone = "";
            this.props.data.tabTitle = ['速运', '海运', '空运'];
            this.props.active = 1;
            addressView.setService(addressService);
            return this.props ? this.props : {};
        },
        render:function() {
            var _this = this;
            var data = this.state.data;
            var address = data["address"],
                typeName = data["typeName"];
            if(address && address.length == 0) {
                data.isHasData = false;
            } else {
                data.isHasData = true;
            }
            Browser = typeof window != 'undefined';
            return ~init;
        }
    });
    if(typeof ReactDOM != "undefined") {
        ReactDOM.render(<PageComponent data={storage}/>, document.getElementById('container'));
    }
    module.exports = PageComponent;
});
